<?php

class Core_Api_Image
{
	/**
	 * @param string $key
	 * @return array
	 */
	function getConfig($key)
	{
		$result = array();

		$table = Nuo::getTable('core/image');

		$select = $table -> select() -> where('resource_key IN (?)', array(
			$key,
			'none'
		)) -> where('is_enabled=1') -> order('sort_order ASC');

		foreach ($table -> fetchAll($select) as $row)
		{
			$result[$row -> photo_key] = array(
				'width' => (int)$row -> width,
				'height' => (int)$row -> height,
				'quality' => (int)$row -> quality,
				'crop' => $row -> crop,
			);
		}
		return $result;
	}

	/**
	 * process from upload with some stockets.
	 * 	createImageFromUpload('photo', $types=array());
	 *
	 * @param string $fieldName upload field name ect: photo
	 * @param string/array $types
	 * @return Core_Table_Model_File
	 * @throws Exception
	 */
	public function process($params, $types = NULL, $engine = NULL)
	{
		
		$filesystem =  Nuo_Filesystem::instance();

		try
		{

			if (!$types)
			{
				$types = 'none';
			}

			if (is_string($types))
			{
				$types = $this -> getConfig($types);
			}

			/**
			 * upload file name
			 * @var string
			 */
			$name = '';

			/**
			 * temporary file name
			 * @var string
			 */
			$tempFile = '';

			if (is_array($params))
			{
				$name = isset($params['name']) ? $params['name'] : '';

				if (isset($params['tmp_name']))
				{
					$tempFile = $params['tmp_name'];
				}
				else
				if (isset($params['url']))
				{
					$tempFile = $params['url'];
				}
				else
				if (isset($params['file']))
				{
					$tempFile = $params['file'];
				}
			}
			else
			if (is_string($params))
			{
				$tempFile = $params;
			}

			if (!$tempFile)
			{
				return NULL;
			}

			$result = array();

			/**
			 * @var WideImage
			 */
			$image = Nuo_Image::loadFromFile($tempFile);

			/**
			 * file extension
			 * @var string
			 */
			$ext = 'jpg';

			/**
			 * pattern for temporary files
			 * @var string
			 */
			$pattern1 = $filesystem->createTempPathPattern($ext, TRUE);

			/**
			 * savet to path pattern
			 * @var string
			 */
			$pattern2 = $filesystem->createPathPattern($ext, TRUE);

			/**
			 * @var array
			 */
			$extra = array();

			/**
			 * @var int
			 */
			$size = 0;

			if (!$engine)
			{
				$engine = Nuo_Storage::instance();
			}

			/**
			 * generate scale version of file path.
			 */
			foreach ($types as $type => $param)
			{
				$newImg = $image -> resizeDown($param['width'], $param['height'], 'outside') 
				-> crop('center', 'middle', $param['width'], $param['height']);
				// create temporary path

				$temp = strtr($pattern1, array('{type}' => $type));

				$path = strtr($pattern2, array('{type}' => $type));

				$newImg -> saveToFile($temp, $param['quality']);

				$tempSize = filesize($temp);

				if ($tempSize > $size)
				{
					$size = $tempSize;
				}

				if ($engine -> put($path, $temp))
				{
					$extra[$type] = $path;
				}
				@unlink($temp);
			}

			$row = Nuo::getTable('core/file') -> fetchNew();
			$row -> name = $name;
			$row -> size = $size;
			$row -> type = 'image/jpg';
			$row -> ext = 'jpg';
			$row -> storage_id = $engine -> getId();
			$row -> path = $pattern2;
			$row -> extra = json_encode($extra);
			$row -> created_at = time();
			$row -> save();

			return $row;
		}
		catch(Exception $e)
		{
			throw $e;
		}
	}

	/**
	 * process all images and return file object associated
	 * @param  array $images
	 * @param  string $type
	 * @param  string $engine
	 * @return array
	 */
	public function processAll($images, $type = NULL, $engine = NULL)
	{

		$files = array();
		foreach ($images as $array)
		{
			$file = self::process($array, 'photo');
			if ($file)
			{
				$files[] = $file;
			}
		}
		return $files;
	}

}
